package com.realtyManage.springboot.Controller;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.pdf.codec.Base64;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.BaseEntity;
import com.realtyManage.springboot.Model.Vo.CouponEntity;
import com.realtyManage.springboot.Service.CommodityService;
import com.realtyManage.springboot.Service.IUserService;
import com.realtyManage.springboot.Utils.HttpClientUtil;
import com.realtyManage.springboot.Utils.IdGen;
import com.realtyManage.springboot.Utils.SysExecRsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.spec.AlgorithmParameterSpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * AesController
 * AES解密
 * @Author 杭州素色网络科技有限公司
 * @Date 2020/01/07
 **/

@Controller
@RequestMapping("/")
public class AesController {

    @Autowired
    private IUserService userService;

    @Autowired
    protected BCryptPasswordEncoder bCryptPasswordEncoder;

    @ResponseBody
    @RequestMapping(value = "/getSessionKey",method = RequestMethod.GET)
    private String getSessionKey(String js_code,String appId, String secret,HttpServletRequest request){
        String sessionKey = null;
       // Map map = new HashMap();
        // 授权（必填）
        String grant_type = "authorization_code";
        // 请求参数
        String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + js_code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpClientUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        try {
            // 解析相应内容（转换成json对象）
            JSONObject json = new JSONObject(sr);
            // net.sf.json.JSONObject json1 = net.sf.json.JSONObject.fromObject(sr);
            // 获取会话密钥（session_key）
            sessionKey = json.get("session_key").toString();
            System.out.println("========sessionKey=========>"+sessionKey);
            // 用户的唯一标识（openid）
            //String openid = (String) json.get("openid").toString();
           // map.put( "session_key",session_key);
            //map.put( "openId",openid );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionKey;
    }

    /**
     * 解密手机号
     * @param encrypdata
     * @param ivdata
     * @param sessionkey
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deciphering",method = RequestMethod.GET)
    private String deciphering(String encrypdata,String ivdata, String sessionkey,HttpServletRequest request){
        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str="";
        try {
            str = decrypt(sessionKey,ivData,encrypData);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("============手机号码================>"+str);
        /*System.out.println("返回前直接存入库中，普通用户");
        //用手机号查询用户信息
        if (str == null){   //此用户不在系统中或未登录
            if (userService.findByTelePhone(str).getId() != null){   //存在系统中但未登录
                System.out.println("==========cz===========");
            }else{    //不存在系统中则自行录入系统
                User user = new User();
                user.setTelephone(str);
                user.setIntegral(0); //没有积分
                user.setPwd(bCryptPasswordEncoder.encode("123456")); //默认密码
                user.setLevel(1);
                user.setStatus(1);
                user.setRegTime(new Date());
                Integer id = userService.insert(user).getId();
            }
        }*/

        //20200229  获取手机号后自动登录系统

        return str;
    }

    //解密
    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}
